package com.ktjy.controller;

import com.ktjy.pojo.SysRight;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.ISysRightService;
import com.ktjy.service.ISysUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class LoginController {
    @Autowired
    ISysUserService iSysUserService;
    @Autowired
    ISysRightService iSysRightService;
    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 跳转到首页
     * @return
     */
    @RequestMapping("/main")
    public String main(){
        return "main";
    }

    /**
     * 处理登录逻辑
     * @return
     */
    @RequestMapping("/dologin")
    public String dologin(@RequestParam("usrName") String usrName,
                          @RequestParam("usrPassword") String usrPassword,
                          HttpServletRequest request,
                          HttpSession session){
        //查询数据库
        SysUser loginUser = iSysUserService.login(usrName, usrPassword);
        if(loginUser!=null){//登录成功
            //根据角色查询权限信息
            List<SysRight> rights = iSysRightService.findByRoleId(loginUser.getUsrRoleId());
            loginUser.getRole().setRights(rights);

            //1.登录用户信息保存到session
            session.setAttribute("loginUser",loginUser);
            //2.跳转到首页
            return "redirect:/main";
        }else{
            //1.给出错误提示
            request.setAttribute("message","用户名或者密码错误");
            //2.跳转登录页面
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //1.销毁session
        session.invalidate();
        //2.跳转登录页面
        return "login";
    }
}
